<template>
  <div>
    <div class="licc-pages-home-manage-top">
      <el-row>
        <el-col :span="6">
          <el-checkbox-group
            v-model="checkList"
            :min="1">
            <el-checkbox label="所有轮播图" @change="checkAllListChage"></el-checkbox>
            <el-checkbox label="显示轮播图" @change="checkShowListChage"></el-checkbox>
            <el-checkbox label="待显示轮播图" @change="checkNoShowListChage"></el-checkbox>
          </el-checkbox-group>
        </el-col>
        <el-col :span="6" :offset="12">
          <el-button type="primary" @click="photoInfoAddButton">添加轮播图</el-button>
          <el-button type="primary" @click="previewPhotoDialogVisible=true">轮播图预览</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="licc-pages-home-manage-table">
      <el-table
        stripe
        border
        :data="photos">
        <el-table-column label="图片信息" width="710">
          <template slot-scope="scope">
            <el-image
              style="width: 700px; height: 213px"
              :src="scope.row.url"
              fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="photoSort" label="图片排序" width="90"></el-table-column>
        <el-table-column prop="createDate" label="添加时间"></el-table-column>
        <el-table-column prop="disabled" label="是否显示" width="90">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.disabled"
              @change="homePhotoSwitchChange(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="150">
          <template slot-scope="scope">
            <el-button @click="deletePhotoClick(scope.row)" type="danger" size="mini">删除</el-button>
            <el-button @click="handlePhotoClick(scope.row)" type="primary" size="mini">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 8, 12, 16]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="photosTotal">
      </el-pagination>
    </div>
    <div>
      <el-dialog
        title="加入首页轮播图显示"
        :visible.sync="photoDisabledDialogVisible"
        width="30%"
        :before-close="handleClose">
        <span>
          <el-form :model="photoInfo" :rules="photoInfoRules" ref="photoInfo">
            <el-form-item label="图片排序：" prop="photoSort"  label-width="100px">
              <el-input v-model="photoInfo.photoSort" placeholder="请输入排序数字"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updatePhotoInfoCancel">取 消</el-button>
          <el-button type="primary" @click="updatePhotoInfoSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <div>
      <el-dialog
        title="轮播图添加"
        :visible.sync="photoAddDialogVisible"
        width="30%"
        :before-close="handleAddClose">
        <span>
          <el-form :model="photoAddInfo" :rules="photoAddInfoRules" ref="photoAddInfo">
            <el-form-item label="图片信息：" :required="true" label-width="100px">
                <!--list-type="picture-card"-->
              <el-upload
                class="avatar-uploader"
                action="http://localhost:8888/shopGoods/data/uploadFile"
                :show-file-list="false"
                :limit="1"
                :on-preview="handlePictureCardPreview"
                :on-exceed="exceedImgThumb"
                :before-upload="beforeUploadImgThumb"
                :on-success="successImgThumb"
                :on-remove="removeImgThumb">
                <!--<i class="el-icon-plus"></i>-->
                <img v-if="photoUrl" :src="photoUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <!--<el-dialog :visible.sync="photoUrlInfoDialogVisible">-->
                <!--<img width="100%" :src="photoUrl" alt="">-->
              <!--</el-dialog>-->
            </el-form-item>
            <el-form-item label="图片排序：" prop="photoSort"  label-width="100px">
              <el-input v-model="photoAddInfo.photoSort" placeholder="请输入排序数字"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addPhotoInfoCancel">取 消</el-button>
          <el-button type="primary" @click="addPhotoInfoSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <div>
      <el-dialog
        title="轮播图排序编辑"
        :visible.sync="photoEditDialogVisible"
        width="30%"
        :before-close="handleEditClose">
        <span>
          <el-form :model="photoEditInfo" :rules="photoEditInfoRules" ref="photoEditInfo">
            <el-form-item label="图片排序：" prop="photoSort"  label-width="100px">
              <el-input v-model="photoEditInfo.photoSort" placeholder="请输入排序数字"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updatePhotoEditInfoCancel">取 消</el-button>
          <el-button type="primary" @click="updatePhotoEditInfoSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <div>
      <el-dialog
        title="轮播图预览"
        :visible.sync="previewPhotoDialogVisible"
        width="45%">
        <span>
          <home-carousel v-if="previewPhotoDialogVisible"></home-carousel>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import pagesApi from '@/api/backstage/pages'
  import HomeCarousel from '../components/homeCarousel'
  export default {
    name: 'Home_page',
    components: {
      HomeCarousel
    },
    data() {
      const validatePhotoSort = (rule, value, callback) => {
        let photoSortRule = /^([1-9]\d{0,2}|1000)$/
        if (value===''){
          callback(new Error('请输入排序数字'));
        } else if (!photoSortRule.test(value)) {
          callback(new Error('排序是1到1000间的数字'));
        } else {
          callback();
        }
      }
      return {
        checkList:['所有轮播图'],
        photos:[],
        currentPage: 1,
        pagesize:8,
        photosTotal:0,
        params:{
          disabled:null
        },
        /** 图片加入显示时显示对话框 **/
        photoDisabledDialogVisible: false,
        /** 图片加入显示时图片信息 **/
        photoInfo:{},
        photoInfoRules:{
          photoSort:[{required: true, trigger: 'blur', validator: validatePhotoSort}]
        },
        /** 轮播图添加页面 **/
        photoAddDialogVisible:false,
        /** 轮播图添加信息 **/
        photoAddInfo:{},
        photoUrl:'',
        photoAddInfoRules:{
          photoSort:[{required: true, trigger: 'blur', validator: validatePhotoSort}],
        },
        photoUrlInfoDialogVisible: false,
        /** 修改排序不显示 **/
        photoEditDialogVisible: false,
        /** 修改排序轮播图信息 **/
        photoEditInfo: '',
        photoEditInfoRules:{
          photoSort:[{required: true, trigger: 'blur', validator: validatePhotoSort}]
        },
        /** 轮播图预览 **/
        previewPhotoDialogVisible: false,
      };
    },
    created() {
      this.initData()
    },
    methods: {
      initData(){
        this.photos = [];
        pagesApi.initHomePage(this.params, this.currentPage, this.pagesize).then(res => {
          this.photos = res.data.records;
          this.photosTotal = res.data.total;
        })
      },
      /** 分页---开始 **/
      handleSizeChange(val) {
        this.pagesize = val;
        this.initData();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.initData();
      },
      /** 分页---结束 **/
      checkAllListChage(value){
        if (value == true) {
          this.params = {};
          this.checkList = ['所有轮播图'];
          this.initData();
        }
      },
      checkShowListChage(value){
        if (value == true) {
          this.params = {
            disabled:1
          };
          this.checkList = ['显示轮播图'];
          this.initData();
        }
      },
      checkNoShowListChage(value){
        if (value == true) {
          this.params = {
            disabled:0
          };
          this.checkList = ['待显示轮播图'];
          this.initData();
        }
      },
      /** 新品推荐或取消推荐按钮 **/
      homePhotoSwitchChange(row){
        if (row.disabled === 1) {
          /** 加入显示 **/
          this.$nextTick(()=>{
            this.$refs['photoInfo'].clearValidate();
          })
          this.photoInfo = row;
          this.photoDisabledDialogVisible = true;
        } else {
          /** 移除显示 **/
          this.$confirm('该操作会将该图片移除轮播图显示，是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let provisionalParams = {
              id: row.id,
              disabled: 0
            }
            pagesApi.updateHomePhotoStatus(provisionalParams).then(res => {
              this.initData();
              this.$notify.success({title: '成功', message: '该图片已成功移除轮播图显示'});
            }).catch(() => {
              this.$notify.error({title: '失败', message: '该图片移除轮播图显示失败，请稍后再试'});
              row.disabled = 1;
            })
          }).catch(() => {
            /** 取消提交 **/
            row.disabled = (row.disabled === 1)?0:1;
            this.$notify.info({title: '取消', message: '已取消操作'});
          });
        }
      },
      /** 加入推荐取消按钮 **/
      updatePhotoInfoCancel(){
        this.photoInfo.disabled = 0;
        this.photoDisabledDialogVisible = false;
      },
      /** 加入推荐确定按钮 **/
      updatePhotoInfoSubmit(){
        this.$refs['photoInfo'].validate(valid => {
          if (valid){
            let provisionalParams = {
              id: this.photoInfo.id,
              photoSort: this.photoInfo.photoSort,
              disabled: 1
            }
            pagesApi.updateHomePhotoStatus(provisionalParams).then(res => {
              this.initData();
              this.$notify.success({title: '成功', message: '该图片已成功添加到轮播图显示'});
              this.photoDisabledDialogVisible = false;
            }).catch(() => {
              this.$notify.error({title: '失败', message: '该图片添加到轮播图显示失败，请稍后再试'});
            })
          } else {
            this.$notify.warning({title:'提示',message:'图片排序数字不合规'});
          }
        })
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            this.photoInfo.disabled = 0;
            done();
          })
          .catch(_ => {});
      },
      /** 商品信息添加 **/
      photoInfoAddButton(){
        this.photoAddInfo = {};
        this.photoUrl = '';
        this.$nextTick(()=>{
          this.$refs['photoAddInfo'].clearValidate();
        })
        this.photoAddDialogVisible = true;
      },
      handleAddClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      handlePictureCardPreview(file){
        this.photoUrl = file.url;
        this.photoUrlInfoDialogVisible = true;
      },
      /** 图片超出数量限制的钩子 **/
      exceedImgThumb(file, fileList){
        this.$notify.warning({title:'提示', message:'只能上传一张图片'});
      },
      /** 图片上传前钩子 **/
      beforeUploadImgThumb(file){
        const isJPG = file.type === 'image/jpeg';
        const isLt1M = file.size / 1024 / 1024 < 4;
        if (!isJPG){
          this.$notify.warning({title:'警告',message:'上传图片只能是JPG格式！'});
        }
        if (!isLt1M){
          this.$notify.warning({title:'警告',message:'上传图片大小不能超过4MB！'});
        }
        return isJPG && isLt1M;
      },
      /** 上传成功钩子 **/
      successImgThumb(response, file, fileList){
        this.photoUrl = response.data[file.name];
      },
      /** 图片移除后钩子 **/
      removeImgThumb(file, fileList){
        this.photoUrl = '';
      },
      /** 取消按钮 **/
      addPhotoInfoCancel(){
        this.photoAddDialogVisible = false;
        this.photoAddInfo = {};
      },
      /** 添加提交按钮 **/
      addPhotoInfoSubmit(){
        this.$refs['photoAddInfo'].validate(valid => {
          if (valid){
            if (this.photoUrl === ''){
              this.$notify.warning({title: '提示', message: '请选择图片信息'});
              return false;
            }
            let photoInfo = {
              url: this.photoUrl,
              type: 20,
              photoSort: this.photoAddInfo.photoSort,
              disabled: 0
            }
            pagesApi.addHomePhotoStatus(photoInfo).then(res => {
              this.initData();
              this.$notify.success({title: '成功', message: '添加图片成功'});
              this.photoAddDialogVisible = false;
            }).catch(() => {
              this.$notify.error({title: '失败', message: '添加图片失败，请稍后再试'});
            })
          } else {
            this.$notify.warning({title:'提示',message:'图片排序数字不合规'});
          }
        })
      },
      /** 图片删除按钮 **/
      deletePhotoClick(row){
        this.$confirm('该操作会将会删除该轮播图，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let provisionalParams = {
            id: row.id
          }
          pagesApi.deleteHomePhotoById(provisionalParams).then(res => {
            this.initData();
            this.$notify.success({title: '成功', message: '该轮播图已成功删除'});
          }).catch(() => {
            this.$notify.error({title: '失败', message: '该轮播图删除失败，请稍后再试'});
          })
        }).catch(() => {
          /** 取消删除 **/
          this.$notify.info({title: '取消', message: '已取消操作'});
        });
      },
      /** 图片编辑按钮 **/
      handlePhotoClick(row){
        this.photoEditInfo = {};
        this.$nextTick(()=>{
          this.$refs['photoEditInfo'].clearValidate();
        })
        this.photoEditInfo = row;
        this.photoEditDialogVisible = true;
      },
      handleEditClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            this.photoEditInfo = {};
            done();
          })
          .catch(_ => {});
      },
      /** 编辑排序取消 **/
      updatePhotoEditInfoCancel(){
        this.photoEditDialogVisible = false;
        this.photoEditInfo = {};
      },
      /** 编辑排序提交 **/
      updatePhotoEditInfoSubmit(){
        this.$refs['photoEditInfo'].validate(valid => {
          if (valid){
            let provisionalParams = {
              id: this.photoEditInfo.id,
              photoSort: this.photoEditInfo.photoSort,
            }
            pagesApi.updateHomePhotoStatus(provisionalParams).then(res => {
              this.initData();
              this.$notify.success({title: '成功', message: '该轮播图修改排序成功'});
              this.photoEditDialogVisible = false;
            }).catch(() => {
              this.$notify.error({title: '失败', message: '该轮播图修改排序失败，请稍后再试'});
            })
          } else {
            this.$notify.warning({title:'提示',message:'图片排序数字不合规'});
          }
        })
      },
    }
  }
</script>
<style>
  .licc-pages-home-manage-top{
    width: 100%;
    height: 50px;
    line-height: 50px;
    min-width: 1100px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
